import { getFileExecName, getImgUrl } from '@/utils';
import { PlusOutlined } from '@ant-design/icons';
import {  Image,  Upload, UploadProps, message } from 'antd';
import { useMemo, useState } from 'react';
import styles from './style.less';
import { getToken } from '@/utils/info';
import { uploadFile } from '@/services/commonServices';
type Props = {
  type?: 'image' | 'file'; //上传类型
  accept?: string;
  length?: number; //文件个数
  size?: number; // 单个文件的大小 单位mb
  templateUrl?: string; //示例图片地址
  value?: Array<any>;
  showOnly?: boolean;
  onChange?: (value: Props['value']) => void;
};
export default (props: Props) => {
  const {
    size = 20,
    length = 1,
    accept = '.jpg,.jpeg,.bmp,.png', // 支持的格式
    value,
    showOnly = false,
    onChange,
  } = props;

  const [previewVsible, setPreviewVsible] = useState(false);
  const [previewUrl, setPreviewUrl] = useState('');

  const fileList = useMemo(
    () =>
      value?.map((item,index) => ({
        url: item,
        status: 'done',
      })),
    [value],
  );

  const uploadProps: UploadProps = {
    maxCount: length,
    listType: 'picture-card',
    accept:accept,
    beforeUpload(file) {
      return new Promise((reoslve, reject) => {
        // 后缀名
        const execName = getFileExecName(file.name);
        if (!!accept && !accept.includes(execName)) {
          message.error(`暂时不支持该格式文件`);
          reject();
        } else if (file.size / 1024 / 1024 > size) {
          message.error(`文件不能超过${size}M`);
          reject();
        } else {
          reoslve();
        }
      });
    },
    customRequest: ({ file }) => {
        uploadFile(file).then((data) => {
          if (!data) return;
          if(length === 1){
            onChange?.([getImgUrl(data)]);
          }else{
            onChange?.([...(value || []), getImgUrl(data)]);
          }
        });
    },
    onRemove(v) {
      onChange?.([]);
    },
    onPreview({url}) {
      const execName = getFileExecName(url);
      if ('.jpg,.jpeg,.bmp,.png'.includes(execName)) {
        setPreviewUrl(url!);
        setPreviewVsible(true);
      }else {
        window.open(url);
      }
    },
  };

  const disabled = useMemo(
    () => showOnly || (!!value?.length && value?.length >= length),
    [length, value, showOnly],
  );
  return (
    <div className={styles.container}>
      <Upload
        name="avatar"
        fileList={fileList}
        {...uploadProps}
        disabled={showOnly}
      >
        {disabled ? null : (
          <>
            <div>
              <PlusOutlined />
              <div style={{ marginTop: 8 }}>上传</div>
            </div>
          </>
        )}
      </Upload>
      <Image
        preview={{
          visible: previewVsible,
          src: previewUrl,
          onVisibleChange: setPreviewVsible,
        }}
      />
    </div>
  );
};
